<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form label-width="120px" ref="formRef" :model="searchValue">
        <el-row>
          <el-col :span="6">
            <el-form-item label="操作时间：" prop="timeRange">
              <el-date-picker
                v-model="searchValue.timeRange"
                type="datetimerange"
                range-separator="—"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="timeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="用户姓名：" prop="creatorName">
              <ns-input v-model="searchValue.creatorName" clearable placeholder="请输入操作人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作内容：" prop="auditType">
              <el-select v-model="searchValue.auditType">
                <el-option
                  v-for="(item, index) in operationList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作对象：" prop="showName">
              <ns-input v-model="searchValue.showName" clearable placeholder="请输入操作对象" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作对象类型：" prop="dataType">
              <el-select v-model="searchValue.dataType">
                <el-option
                  v-for="(item, index) in operationTypeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button @click="searchReset" plain v-hasPermi="['system:asset-log:search']"
              >重置</el-button
            >
            <el-button @click="search" plain v-hasPermi="['system:asset-log:search']"
              >搜索</el-button
            >
            <el-button type="primary" @click="openForm" v-hasPermi="['system:asset-log:set']">
              日志范围设置</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button type="primary" @click="handleExport">导出</el-button>
      </el-form-item>
      <AsyncTable
        v-bind="tableInfo"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="changeTable"
      />
    </ContentWrap>
    <DialogForm ref="dialogFormRef" @success="search" />
  </div>
</template>

<script setup lang="tsx">
import DialogForm from './components/dialogFormRef.vue'
import { ElMessage } from 'element-plus'
import AsyncTable from '@/components/AsyncTable'
import { useRouter } from 'vue-router'
import * as assetChangeLogApi from '@/api/assetChangeLog/index'
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import { ElLoading } from 'element-plus'
import dayjs from 'dayjs'
import { checkPermi } from '@/utils/permission'
import { classificationChangeRender, levelChangeRender } from '@/utils/commonRender'
import download from '@/utils/download'

const message = useMessage() // 消息弹窗
const tableRef = ref()
const formRef = ref()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const router = useRouter()
const ids = ref<string[]>([])
const reportChartRef = ref()
const statusMap = new Map([
  [0, '进行中'],
  [1, '已完成'],
  [2, '错误']
])
const searchValue = ref({
  name: '',
  timeRange: '',
  startTime: '',
  endTime: '',
  creatorName: '',
  auditType: '',
  showName: '',
  levelChange: '',
  classificationChange: ''
})

const operationTypeList = [
  {
    label: '文件',
    value: 'file'
  },
  {
    label: '表',
    value: 'table'
  },
  {
    label: '字段',
    value: 'column'
  },
  {
    label: '数据库',
    value: 'db'
  },
  {
    label: '数据源',
    value: 'dbSource'
  },
  {
    label: 'schema',
    value: 'schema'
  }
]
const operationList = [
  {
    label: '新增',
    value: '新增'
  },
  {
    label: '删除',
    value: '删除'
  },
  {
    label: '修改',
    value: '修改'
  },
  {
    label: '撤回',
    value: '撤回'
  },
  {
    label: '审核通过',
    value: '审核通过'
  },
  {
    label: '审核拒绝',
    value: '审核拒绝'
  },
  {
    label: '提交审核',
    value: '提交审核'
  },
  {
    label: '迁移',
    value: '迁移'
  },
  {
    label: '自动降敏',
    value: '自动降敏'
  }
]

/**
 * @description: 选取列表时获取列表id
 * @param {*} val
 */
const changeTable = (val) => {
  ids.value = []
  val.map((item) => {
    ids.value.push(item.id)
  })
}
const searchReset = () => {
  searchValue.value = {
    name: '',
    timeRange: '',
    startTime: '',
    endTime: '',
    creatorName: '',
    auditType: '',
    showName: ''
  }
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}

const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const tableInfo = reactive({
  columns: [
    // {
    //   type: 'selection'
    // },
    { label: '操作时间', prop: 'createTime' },
    { label: '用户姓名', prop: 'creatorName' },
    { label: '员工编号', prop: 'userName' },
    { label: '操作内容', prop: 'auditType' },
    { label: '操作对象', prop: 'showName' },
    {
      label: '操作对象类型',
      render: ({ row }) => {
        return <>{operationTypeList.find((item) => item.value === row.dataType)?.label}</>
      }
    },
    { label: '分级变更情况', render: levelChangeRender },
    { label: '分类变更情况', render: classificationChangeRender },
    {
      label: '操作项',
      width: '150px',
      render: ({ row }) => {
        return (
          <>
            {checkPermi(['system:asset-log:detail']) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  openDetail(row)
                }}
              >
                查看
              </el-button>
            )}
          </>
        )
      }
    }
  ],
  data: []
})

const pageParams = ref({
  page: 1,
  pageSize: 10
})
const fetchData = async ({ page, pageSize }) => {
  pageParams.value = {
    page,
    pageSize
  }
  const { data, count } = await assetChangeLogApi.levelHistoryPageHistory({
    page,
    pageSize,
    ...searchValue.value
  })
  console.log('data', data)
  // currentId.value = data[0].id
  return { data, count }
}

//导出
const handleExport = async () => {
  const valid = await proxy.$modal.confirm('确定要导出当前页内容吗？')
  if (!valid) {
    return
  }
  const data = await assetChangeLogApi.levelHistoryExport({
    ...searchValue.value,
    ...pageParams.value
  })

  download.excel(data, '资产变更日志.xlsx')
}

/** 添加/修改操作 */
const dialogFormRef = ref()
const openForm = () => {
  dialogFormRef.value.open()
}

const getList = () => {
  tableRef.value.fetchData()
}

const timeChange = (e) => {
  console.log('e', e)
  searchValue.value.startTime = dayjs(e[0]).format('YYYY-MM-DD HH:mm:ss')
  searchValue.value.endTime = dayjs(e[1]).format('YYYY-MM-DD HH:mm:ss')
}

const openDetail = (row) => {
  // console.log('row', row)
  if (row.dataType == 'db' || row.dataType == 'dbSource' || row.dataType == 'schema') {
    router.push({
      path: '/asset/dataBaseDetail',
      query: {
        id: row.dataSourceId
      }
    })
  } else {
    proxy?.$Drawer({
      params: {
        ...row,
        type: row.handClassificationName ? `人工` : row.classificationName ? `自动` : '--',
        callBack: () => {
          tableRef.value.resetPage()
          tableRef.value.fetchData()
        }
      },
      title: `查看分类分级详情`,
      size: '40%',
      component: import('@/views/assetManage/components/baseInfo.vue')
    })
  }
}
</script>

<style lang="scss"></style>
